package com.ccys.app.controller;

import cn.hutool.core.date.DateUtil;
import com.ccys.app.service.MemberService;
import com.ccys.common.vo.ResponseResultApp;
import com.ccys.db.cache.UserUtil;
import com.ccys.db.dto.app.home.UpdateDeviceDto;
import com.ccys.db.entity.TblMember;
import com.ccys.db.mapper.TblMemberMapper;
import com.ccys.db.mapper.TblSupplierMapper;
import com.ccys.db.vo.app.home.*;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author：XLY
 * @Date：2024/1/15 0015
 */

@RestController
@RequestMapping("/home")
@Api(tags = "Home")
@Slf4j
public class HomeController {


    @Resource
    private TblSupplierMapper mapper;

    @Resource
    private MemberService memberService;

    @Resource
    private TblMemberMapper memberMapper;

//    /**
//     * 1    practitioner  - GP
//     * 2    mental_wellness  - mental wellness
//     * 3    paediatrician  -  paediatrician
//     * 4    supervised_art  -  保留历史数据
//     * 5    home_based_health_screening  -  home_based_health_screening
//     * 6    pre_departure_test  -  保留历史数据
//     * 7    obstetrics_and_gynaecology  -  obstetrics_and_gynaecology
//     * 8    Think well  -  Think well
//     */
//   private HashMap<Integer, String > countryServiceTypeMap  = new HashMap<Integer, String>(){{
//        put(1,"practitioner");
//        put(2,"mental_wellness");
//        put(3,"paediatrician");
//        put(4,"supervised_art");
//        put(5,"home_based_health_screening");
//        put(6,"pre_departure_test");
//        put(7,"obstetrics_and_gynaecology");
//        put(8,"Think well");
//    }};


    @ApiOperation("home/1")
    @GetMapping("GetBookingCdmpRebuy")
    public ResponseResultApp<CdmpRebuyVo.CdmpRebuyResVo> getBookingCdmpRebuy() {
        //tbl_booking_cdmp_package 最近的一条数据,status为0或者1的
        CdmpRebuyVo.CdmpRebuyResVo res = new CdmpRebuyVo.CdmpRebuyResVo();
        String curLoginUserId = UserUtil.getCurLoginUserId();
        //.
        CdmpRebuyVo rebuyVo = mapper.getBookingCdmpRebuy(curLoginUserId);
        if (Objects.nonNull(rebuyVo)) {
            res.setBookingId(rebuyVo.getBookingId());
            res.setCdmpPackageName(rebuyVo.getCdmpPackageName());
            //计算days_left 总的天数 - 第一购买没付钱的时间
            Date bookingPaymentAt = rebuyVo.getBookingPaymentAt();
            if (Objects.nonNull(bookingPaymentAt)) {
                int betweenDay = (int) DateUtil.betweenDay(bookingPaymentAt, new Date(), false);
                Integer allDay = rebuyVo.getAllowReactivatePurchaseFor();
                int days_left = allDay - betweenDay;
                res.setDaysLeft(days_left);
            }
        }
        return ResponseResultApp.success(res);

    }

    @ApiOperation("home/2")
    @GetMapping("GetGuides")
    public ResponseResultApp<List<GuideVo>> getGuides() {
        // 首先查询tbl_plan_benefit_member中，
        // 当前登录用户是否有可用的benefit，然后根据benefit设置的on boarding screens查询
        // 查询对象为tbl_onboarding_screens以及detail
        String curLoginUserId = UserUtil.getCurLoginUserId();
        //.
        List<GuideVo> guides = mapper.getGuides(curLoginUserId);
        return ResponseResultApp.success(guides);
    }


    @ApiOperation("home/3")
    @GetMapping("GetInAppServices")
    public ResponseResultApp<List<InAppServicesVo>> getInAppServices() {
        // dynamic = onDemandDisplay
        // 查询病人当前国家的 tbl_country_service_type
        // icon全部为空字符串，
        // on_available为:当前这项服务是否有医生可以预约，
        // 通过服务对应的类型关联到specialisation的identification关联到本国是否有可以预约的医生
        // GP的话就查询本国是否有可预约的GP医生
        // 用医生表里的country_of_residence
        /**
         * 1    practitioner  - GP
         * 2    mental_wellness  - mental wellness
         * 3    paediatrician  -  paediatrician
         * 4    supervised_art  -  保留历史数据
         * 5    home_based_health_screening  -  home_based_health_screening
         * 6    pre_departure_test  -  保留历史数据
         * 7    obstetrics_and_gynaecology  -  obstetrics_and_gynaecology
         * 8    Think well  -  Think well
         */
        /**
         * foreach (DataRow row in inAppServiceInfo.Tables[0].Rows)
         *                 {
         *                     var title = string.Empty;
         *                     var subTitle = string.Empty;
         *                     int serviceType = Convert.ToInt32(row["service_type"]);
         *                     bool isAddedService = true;
         *
         *                     #region service type logic
         *                     switch (serviceType)
         *                     {
         *                         case (int)ServiceType.SERVICE_TYPE_PRACTITIONER: (1)
         *                             title = Message.ON_DEMAND_VIDEO_CONSULTATION;
         *                             subTitle = Message.GENERAL_PRACTITIONER;
         *                             break;
         *                         case (int)ServiceType.SERVICE_TYPE_MENTAL_WELLNESS: (2)
         *                             title = Message.MENTAL_WELLNESS;
         *                             break;
         *                         case (int)ServiceType.SERVICE_TYPE_PAEDIATRICIAN: (3)
         *                             title = Message.PAEDIATRICIAN;
         *                             break;
         *                         case (int)ServiceType.SERVICE_TYPE_SUPERVISED_ART: (4)
         *                             title = Message.SUPERVISED_ART;
         *                             subTitle = "For Covid-19";
         *                             break;
         *                         case (int)ServiceType.SERVICE_TYPE_HOME_BASED_HEALTH_SCREENING: (5)
         *                             title = "HBHS";
         *                             subTitle = Message.HOME_BASED_HEALTH_SCREENING;
         *                             break;
         *                         case (int)ServiceType.SERVICE_TYPE_PRE_DEPARTURE_TEST: (6)
         *                             title = Message.PRE_DEPARTURE_TEST;
         *                             subTitle = "For Travellers";
         *                             break;
         *                         case (int)ServiceType.SERVICE_TYPE_OBSTETRICS_AND_GYNAECOLOGY: (7)
         *                             title = Message.OBSTETRICS_AND_GYNAECOLOGY;
         *                             break;
         *                         case (int)ServiceType.SERVICE_TYPE_THINK_WELL: (8)
         *                             isAddedService = CheckProfileMemberWithBenefit(memberId);
         *                             title = "Think Well";
         *                             subTitle = Message.TEXT_CHAT_WITH_PSYCHOLOGIST;
         *                             break;
         *                         case (int)ServiceType.SERVICE_TYPE_UROLOGY: (9)
         *                             title = Message.UROLOGY;
         *                             break;
         *                         case (int)ServiceType.SERVICE_TYPE_GASTRO: (10)
         *                             title = Message.GASTROENTEROLOGY;
         *                             break;
         *                         case (int)ServiceType.SERVICE_TYPE_CARDIO: (11)
         *                             title = Message.CARDIOLOGY;
         *                             break;
         *                         case (int)ServiceType.SERVICE_TYPE_ORTHOPAEDIC: (12)
         *                             title = Message.ORTHOPAEDIC;
         *                             break;
         *                         case (int)ServiceType.SERVICE_TYPE_DERMATOLOGY: (13)
         *                             title = Message.DERMATOLOGY;
         *                             break;
         *                         case (int)ServiceType.SERVICE_TYPE_OPHTHALMOLOGY: (14)
         *                             title = Message.OPHTHALMOLOGY;
         *                             break;
         *                         case (int)ServiceType.SERVICE_TYPE_RENAL_MEDICINE: (15)
         *                             title = Message.RENAL_MEDICINE;
         *                             break;
         *                         case (int)ServiceType.SERVICE_TYPE_ENDOCRINOLOGY: (16)
         *                             title = Message.ENDOCRINOLOGY;
         *                             break;
         *                         case (int)ServiceType.SERVICE_TYPE_NUTRITIONIST: (17)
         *                             title = Message.NUTRITIONIST;
         *                             break;
         *                     }
         */
        /**
         * The message.xxx is the translation language english/indo/Vietnam
         * ON_DEMAND_VIDEO_CONSULTATION - On Demand Video Consultation/Konsultasi Video Sesuai Permintaan/Tư vấn qua video theo yêu cầu
         * GENERAL_PRACTITIONER - General Practitioner/Dokter Umum/Bác sĩ đa khoa
         * MENTAL_WELLNESS - Mental Wellness/Kesehatan Mental/Sức khỏe tinh thần
         * PAEDIATRICIAN - Paediatrics/Dokter Spesialis Anak/Bác sĩ nhi khoa
         * SUPERVISED_ART - Supervised ART/Supervised ART/Xét nghiệm nhanh kháng nguyên (ART) có giám sát
         * HOME_BASED_HEALTH_SCREENING - Home Based Health Screening/Skrining Kesehatan di Rumah/Sàng lọc sức khoẻ tại nhà
         * PRE_DEPARTURE_TEST - Pre Departure Test/Pre Departure Test/Xét nghiệm trước khi xuất cảnh
         * OBSTETRICS_AND_GYNAECOLOGY - Obstetrics & Gynaecology/Obstetri & Ginekologi/Sản phụ khoa
         * TEXT_CHAT_WITH_PSYCHOLOGIST - Text-chat with a psychologist/Text-chat with a psychologist/Text-chat with a psychologist
         * UROLOGY - Urology
         * GASTROENTEROLOGY - Gastroenterology
         * CARDIOLOGY - Cardiology
         * ORTHOPAEDIC - Orthopaedics
         * DERMATOLOGY - Dermatology
         * OPHTHALMOLOGY - Ophthalmology
         * RENAL_MEDICINE - Renal Medicine
         * ENDOCRINOLOGY - Endocrinology
         * NUTRITIONIST - Nutritionist
         */
        String curLoginUserId = UserUtil.getCurLoginUserId();
        //.
        List<InAppServicesVo> res = mapper.getInAppServices(curLoginUserId);
        if (CollectionUtils.isNotEmpty(res)) {
            res.forEach(x -> {
                String title = "";
                String subTitle = "";
                switch (x.getServiceType()) {
                    case 1:
                        title = "On Demand Video Consultation";
                        subTitle = "General Practitioner";
                        break;
                    case 2:
                        title = "Mental Wellness";
                        break;
                    case 3:
                        title = "Paediatrics";
                        break;
                    case 4:
                        title = "Supervised ART";
                        subTitle = "For Covid-19";
                        break;
                    case 5:
                        title = "HBHS";
                        subTitle = "Home Based Health Screening";
                        break;
                    case 6:
                        title = "Pre Departure Test";
                        subTitle = "For Travellers";
                        break;
                    case 7:
                        title = "Obstetrics & Gynaecology";
                        break;
                    case 8:

                        title = "Think Well";
                        subTitle = "Text-chat with a psychologist";
                        break;
                    case 9:
                        title = "Urology";
                        break;
                    case 10:
                        title = "Gastroenterology";
                        break;
                    case 11:
                        title = "Cardiology";
                        break;
                    case 12:
                        title = "Orthopaedics";
                        break;
                    case 13:
                        title = "Dermatology";
                        break;
                    case 14:
                        title = "Ophthalmology";
                        break;
                    case 15:
                        title = "Renal Medicine";
                        break;
                    case 16:
                        title = "Endocrinology";
                        break;
                    case 17:
                        title = "Nutritionist";
                        break;
                    default:
                        title = "";
                        break;
                }

                x.setTitle(title);
                x.setSubtitle(subTitle);
            });
        }
        return ResponseResultApp.success(res);
    }

    @ApiOperation("home/4")
    @GetMapping("GetNotificationCount")
    public ResponseResultApp<Map<String, Integer>> getNotificationCount() {
        String curLoginUserId = UserUtil.getCurLoginUserId();
        //.
        Integer count = mapper.getNotificationCount(curLoginUserId);
        Map<String, Integer> res = Maps.newHashMap();
        res.put("notification_count", count);
        return ResponseResultApp.success(res);
    }


    @ApiOperation("home/5")
    @PostMapping("UpdateDevice")
    public ResponseResultApp updateDevice(@RequestBody UpdateDeviceDto dto) {
        //device_id 推送标识，前端传入的push_notification_token
        //device_type 设备 1ios 2 android
        String curLoginUserId = UserUtil.getCurLoginUserId();
        //.
        TblMember member = new TblMember();
        member.setId(curLoginUserId);
        member.setDeviceId(dto.getPush_notification_token());
        member.setDeviceType(dto.getDevice_type());
        memberService.insertOrUpdate(member);
        return ResponseResultApp.success();
    }

    @ApiOperation("home/6")
    @GetMapping("CancelPushNotiReactive")
    public ResponseResultApp cancelPushNotiReactive(){
//      dal.ExecuteScalar("delete tbl_Booking_ReactivePayment_Log WHERE mem_id='" + account_id + "'");
        return ResponseResultApp.success();
    }


    @ApiOperation("home/7")
    @GetMapping("GetActiveBooking")
    public ResponseResultApp<List<ActiveBookingVo>> getActiveBooking() {

        String curLoginUserId = UserUtil.getCurLoginUserId();
        //.
        List<ActiveBookingVo> res = mapper.getActiveBooking(curLoginUserId);
        return ResponseResultApp.success(res);
    }


    @ApiOperation("home/9")
    @GetMapping("GetLatestAppointment")
    public ResponseResultApp<LatestAppointmentVo> getLatestAppointment(String country_id) {
        // home_notification为满足条件的最新发布时间的一条news,
        // singtel_is_active为查询当前病人是否有购买sintel的subscription
        // (查询TblPlanBenefitMember为subscription类型，关联的TblPlanSubscriptionSintelOrder不为空),
        // thinkwell_campaign暂时写死，
        // TODO: 2024/1/16 0016 备注一下目前没有campaign的需求
        // appointment为目前生效中最近一次预约
        LatestAppointmentVo res = new LatestAppointmentVo();
        String curLoginUserId = UserUtil.getCurLoginUserId();
        //.
        //查询home_notification
        LatestAppointmentVo.HomeNotification notification = mapper.getLatestHomeNotification(curLoginUserId);
//        String objectParams = notification.getObjectParams();
        //todo photo,titile,short_description,content,is_show_content,service_type,is_show_proceed,url_redirect
        res.setHomeNotification(notification);
        //查询appointment
        //todo document_required
        LatestAppointmentVo.AppointmentVo appointment = mapper.getLatestAppointment(curLoginUserId);
        if (Objects.nonNull(appointment)) {
            //service_type
//            when @prm_specialisation_id = 1 then 3 -- Paed
//            when @prm_specialisation_id in (2,3) then 2 -- MW
//            when @prm_specialisation_id = 4 then 7 -- OBSTETRICS_AND_GYNAECOLOGY
//            when @prm_specialisation_id = 5 then 8 -- Think Well
//            when @prm_specialisation_id = 6 then 9 -- Urology
//            when @prm_specialisation_id = 7 then 10 -- Gastroenterology
//            when @prm_specialisation_id = 8 then 11 -- Cardiology
//            when @prm_specialisation_id = 9 then 12 -- Orthopaedic
//            when @prm_specialisation_id = 10 then 13 -- Dermatology
//            when @prm_specialisation_id = 11 then 14 -- Ophthalmology
//            when @prm_specialisation_id = 12 then 15 -- Renal Medicine
//            when @prm_specialisation_id = 13 then 16 -- Endocrinology
//            when @prm_specialisation_id = 14 then 17 -- Nutritionist
            String specialisationId = appointment.getSpecialisationId();
            if (StringUtils.isNotEmpty(specialisationId)) {
                switch (specialisationId) {
                    case "1":
                        appointment.setServiceType(3);
                        break;
                    case "2":
                    case "3":
                        appointment.setServiceType(2);
                        break;
                    case "4":
                        appointment.setServiceType(7);
                        break;
                    case "5":
                        appointment.setServiceType(8);
                        break;
                    case "6":
                        appointment.setServiceType(9);
                        break;
                    case "7":
                        appointment.setServiceType(10);
                        break;
                    case "8":
                        appointment.setServiceType(11);
                        break;
                    case "9":
                        appointment.setServiceType(12);
                        break;
                    case "10":
                        appointment.setServiceType(13);
                        break;
                    case "11":
                        appointment.setServiceType(14);
                        break;
                    case "12":
                        appointment.setServiceType(15);
                        break;
                    case "13":
                        appointment.setServiceType(16);
                        break;
                    case "14":
                        appointment.setServiceType(17);
                        break;
                    default:
                        break;
                }

            }
        }
        res.setAppointment(appointment);
        //查询singtel_is_active
        //TblPlanBenefitMember.correlationid = sintel_order的order.id
        Integer singtelIsActive = mapper.getSingtelIsActive(curLoginUserId);
        res.setSingtelIsActive(Objects.nonNull(singtelIsActive) && singtelIsActive == 1);
        return ResponseResultApp.success(res);
    }


    @ApiOperation("home/10")
    @GetMapping("GetActiveAction")
    public ResponseResultApp<ActiveActionVo> getActiveAction() {

        String curLoginUserId = UserUtil.getCurLoginUserId();
        //.
        TblMember member = memberMapper.selectByPrimaryKey(curLoginUserId);
        Integer canShowProfileEmailActivated = member.getCanShowProfileEmailActivated();
        ActiveActionVo vo = new ActiveActionVo();
        vo.setProfile_email_activated(canShowProfileEmailActivated == 1);
        vo.setProfile_email_activated_message("You are eligible for enhanced telemedicine benefits.\\r\\n\\r\\nYour corporate / corporate-dependant profile has now been created.");

        List<ActiveActionVo.subscriptionInvitationVo> subscriptionInvitations = mapper.getSubscriptionInvitations(curLoginUserId);
        List<ActiveActionVo.SubscriptionRemovalVo> subscriptionRemovals = mapper.getSubscriptionRemovals(curLoginUserId);
        List<ActiveActionVo.DependantInvitationVo> dependantInvitations = mapper.getDependantInvitations(curLoginUserId);
        List<ActiveActionVo.SharingChildInvitationVo> sharingChildInvitations = mapper.getSharingChildInvitations(curLoginUserId);


        vo.setSubscription_invitations(subscriptionInvitations);
        vo.setSubscription_removals(subscriptionRemovals);
        vo.setDependant_invitations(dependantInvitations);
        vo.setSharing_child_invitations(sharingChildInvitations);

        ActiveActionVo res = new ActiveActionVo();
        return ResponseResultApp.success(res);
    }


    @ApiOperation("home/11")
    @GetMapping("CanShowPaypalPrompt")
    public ResponseResultApp<String> canShowPaypalPrompt() {
        String curLoginUserId = UserUtil.getCurLoginUserId();
        //.
        String res = mapper.canShowPaypalPrompt(curLoginUserId);
        return ResponseResultApp.success(res);
    }


}
